import React from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import _ from 'lodash';
import qs from 'qs';

import { addTab } from '@/utils/utils';
import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Card,
  Row,
  Col,
  Button,
  Input,
  Table,
  Divider,
  Pagination,
  Spin,
} from 'antd';
import '@ant-design/compatible/assets/index.css';

import { TableListData } from './data';

const tableValueName = ['投递收费', '用户取件收费', '用户取件超时收费', '投递人取回超时收费', '寄存收费'];
const dataValueName = ['useP109', 'userUseP109', 'overtimeP109', 'detentionP109', 'depositP109'];
const datavalueItem = [
  'cgdx',
  'cgzx',
  'cgxx',
  'cgcxx',
  'kdx',
  'kzx',
  'kxx',
  'kcxx',
  'cgwjx',
  'kwjx',
  'cgcdx',
  'kcdx',
];
const { pathname } = window.location;

interface CabinetPlansListProps extends FormComponentProps {
  dispatch: Dispatch;
  loading: boolean;
  dataInfo: TableListData;
  screen: string;
  hasPath: boolean;
  spinning:boolean;
}

interface CabinetPlansListState {
  searchValues: any;
}

@connect((state: any) => {
  const {
    cabinetPlansList: { dataInfo, spinning },
    global: { screen, hasPath },
    loading,
  } = state;
  return {
    dataInfo,
    screen,
    hasPath,
    spinning,
    loading: loading.effects['cabinetPlansList/fetch'],
  };
})

class CabinetPlansListElem extends React.Component<CabinetPlansListProps, CabinetPlansListState> {
  columns: any = [
    {
      title: '套餐名称',
      dataIndex: 'title',
      align: 'center',
      width: 120,
      render: (text: string, row: any, index: number) => {
        const values = index === 0
          ? { children: text, props: { rowSpan: 5 } }
          : { props: { colSpan: 0 } };
        return values;
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      align: 'center',
      render: (text: string, row: any, index: number) => {
        const values = index === 0
          ? { children: text, props: { rowSpan: 5 } }
          : { props: { colSpan: 0 } };
        return values;
      },
    },
    {
      title: '项目',
      dataIndex: 'jekect',
      align: 'center',
      width: 180,
    },
    {
      title: '常规箱体(价格单位：分)',
      align: 'center',
      children: [
        { title: '超大箱', dataIndex: 'cgcdx', align: 'center' },
        { title: '大箱', dataIndex: 'cgdx', align: 'center' },
        { title: '中箱', dataIndex: 'cgzx', align: 'center' },
        { title: '小箱', dataIndex: 'cgxx', align: 'center' },
        { title: '超小箱', dataIndex: 'cgcxx', align: 'center' },
        { title: '文件箱', dataIndex: 'cgwjx', align: 'center' },
      ],
    },
    {
      title: '宽箱体(价格单位：分)',
      align: 'center',
      children: [
        { title: '超大箱', dataIndex: 'kcdx', align: 'center' },
        { title: '大箱', dataIndex: 'kdx', align: 'center' },
        { title: '中箱', dataIndex: 'kzx', align: 'center' },
        { title: '小箱', dataIndex: 'kxx', align: 'center' },
        { title: '超小箱', dataIndex: 'kcxx', align: 'center' },
        { title: '文件箱', dataIndex: 'kwjx', align: 'center' },
      ],
    },
    {
      title: '操作',
      align: 'center',
      width: 120,
      fixed: 'right',
      render: (text: string, record: any, index: number) => {
        const values = index === 0
          ? {
            props: { rowSpan: 5 },
            children: (
              <>
                <div>
                  <span
                    className="operLink"
                    onClick={() => this.handleEditCabinetPlans(record.listId, record.title)}
                  >
                    编辑
                  </span>
                  <Divider type="vertical" />
                  <span
                    className="operLink"
                    onClick={() => this.handleShowCabinetPlans(record.listId, record.title)}
                  >
                    详情
                  </span>
                </div>
                <span
                  className="operLink"
                  onClick={() => this.handleUpdateLogs(record.listId)}
                >
                  修改日志
                </span>
              </>
            ),
          }
          : { props: { colSpan: 0 } };
        return values;
      },
    },
  ]

  state: CabinetPlansListState = {
    searchValues: {
      name: '',
      pageIndex: 1,
      pageSize: 20,
    },
  }


  static getDerivedStateFromProps(nextProps: any, preState: any) {
    const { location: { query } } = nextProps;
    const { pageIndex, pageSize, ...values } = query;
    return {
      searchValues: {
        ...values,
        pageIndex: Number(pageIndex) || 1,
        pageSize: Number(pageSize) || 20,
      },
    };
  }

  componentDidMount() {
    this.setFieldsValue();

    const { dataInfo, hasPath } = this.props;
    if (dataInfo?.list?.length && !hasPath) return;

    if (hasPath) {
      const { dispatch } = this.props;
      dispatch({ type: 'global/clearPath' });
    }

    this.fetchDataValues();
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    if (!_.isEqual(this.state, prevState)) {
      this.setFieldsValue();
      this.fetchDataValues();
    }
  }

  setFieldsValue = () => { // 设置表单
    const {
      searchValues: {
        pageIndex,
        pageSize,
        ...values
      },
    } = this.state;

    const params = { ...values };

    const { form: { setFieldsValue } } = this.props;
    setFieldsValue(params);
  }


  fetchDataValues = () => this.fetchAction('fetch', this.getQueryParams());

  getQueryParams = () => {
    const { searchValues } = this.state;
    return searchValues;
  }

  /**
   * 新建套餐
   */
  handleAddCabinetPlans = () => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '新建套餐',
      url: `${pathname}/add`,
    });
  }

  /**
   * 编辑套餐
   */
  handleEditCabinetPlans = (id: number, name: string) => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `编辑${name}`,
      url: `${pathname}/edit?id=${id}`,
    });
  }

  /**
   * 查看套餐
   */
  handleShowCabinetPlans = (id: number, name: string) => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `查看${name}`,
      url: `${pathname}/detail?id=${id}`,
    });
  }

  /**
   * 更改日志
   */
  handleUpdateLogs = (id: number) => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '柜体套餐日志',
      url: `${pathname}/logs?tariffId=${id}`,
    });
  }

  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();

    const { form: { validateFields } } = this.props;
    validateFields((errors, values) => {
      if (errors) return;

      const query = {
        ...values,
        pageIndex: 1,
        pageSize: 20,
      };

      const { dispatch } = this.props;
      addTab(dispatch, {
        name: '柜体套餐',
        url: `${pathname}?${qs.stringify(query)}`,
        isTopMenu: true,
      });
    });
  }

  handleReset = () => {
    const { form: { resetFields } } = this.props;
    resetFields();

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '柜体套餐',
      url: pathname,
      isTopMenu: true,
    });
  }

  handleChangePage: any = (pageIndex: number, pageSize: number) => {
    const { searchValues } = this.state;
    const query = { ...searchValues, pageIndex, pageSize };

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '柜体套餐',
      url: `${pathname}?${qs.stringify(query)}`,
      isTopMenu: true,
    });
  }

  fetchAction = (typeName: string, payload: any = {}) => {
    const { dispatch } = this.props;
    dispatch({
      type: `cabinetPlansList/${typeName}`,
      payload,
    });
  }

  render() {
    const { searchValues: { pageIndex } } = this.state;
    const {
      form: { getFieldDecorator },
      dataInfo,
      loading,
      screen,
      spinning,
    } = this.props;

    const dataList = dataInfo.list ? dataInfo.list.map((item: any) => {
      const value = [];
      for (let i = 0; i < 5; i += 1) {
        value.push({
          id: i,
          title: item.name,
          status: item.valid === 1 ? '有效' : '无效',
          jekect: tableValueName[i],
          listId: item.id,
        });
        let changeIndex: number | string = 0;
        for (let j = 0; j < 12; j += 1) {
          if (j < 9) {
            changeIndex = `0${j + 1}`;
          } else {
            changeIndex = j + 1;
          }
          value[i][datavalueItem[j]] = item[`${dataValueName[i]}${changeIndex}`];
        }
      }
      return value;
    }) : [];

    if (screen === 'sm' || screen === 'lg') {
      delete this.columns[this.columns.length - 1].fixed;
    } else if (screen === 'md') {
      this.columns[this.columns.length - 1].fixed = 'right';
    }

    return (
      <>
        <PageHeader />

        <Card bordered={false} className="searchForm">
          <Form className="tableListForm" onSubmit={this.handleSearch}>
            <Row gutter={12} justify="space-between">
              <Col md={6} sm={24}>
                <Form.Item label="套餐名称" colon={false}>
                  {getFieldDecorator('name')(
                    <Input allowClear placeholder="请输入" />,
                  )}
                </Form.Item>
              </Col>
              <Col md={6} sm={24}>
                <div className="flexFeView">
                  <Button
                    type="primary"
                    htmlType="submit"
                    className="smallButton"
                  >
                    查询
                  </Button>
                  <Button
                    className="addButton smallButton marginL16"
                    type="primary"
                    onClick={this.handleReset}
                  >重置
                  </Button>
                </div>
              </Col>
            </Row>
          </Form>
        </Card>

        <Card bordered={false} className="tableList">
          <Spin spinning={spinning}>
            <div className="tableBtns">
              <Button
                className="smallButton marginB12"
                type="primary"
                size="small"
                onClick={this.handleAddCabinetPlans}
              >
                新建套餐
              </Button>
            </div>
            {dataList.map((item: any) => (
              <Table
                rowKey="id"
                key={item[0].listId}
                columns={this.columns}
                className="otherTable marginB20"
                dataSource={item}
                pagination={false}
                loading={loading}
                scroll={{ x: 1400 }}
              />
            ))}
            <Pagination
              className="flexFeView"
              current={pageIndex}
              total={dataInfo ? dataInfo.count : 0}
              showSizeChanger
              showQuickJumper
              showTotal={() => `共${dataInfo.count || 0}条数据`}
              onChange={this.handleChangePage}
              onShowSizeChange={this.handleChangePage}
              style={{
                paddingBottom: 20,
                paddingRight: 24,
              }}
            />
          </Spin>
        </Card>
      </>
    );
  }
}

export default Form.create<CabinetPlansListProps>()(CabinetPlansListElem);
